package zhouyang;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<Integer> futureTask =new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
            try {
                TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            return 1024;
        });
        new Thread(futureTask,"t1").start();
        System.out.println("---继续");
//        System.out.println(futureTask.get());//只要出现get方法，不管是否计算完成都阻塞等待结果出来再运行
//        System.out.println(futureTask.get(2L,TimeUnit.SECONDS));//过时不侯
        //不要阻塞，用轮询替代阻塞
        while (true){
            if (futureTask.isDone()){
                System.out.println("---result:"+futureTask.get());
                break;
            }else {
                System.out.println("还在计算中");
            }
        }
    }
}
